<template>
  <div>
    <a-card title="免修情况统计" :bordered="false">
      <a-form layout="inline" :form="form" @submit="handleSubmit">
        <a-form-item label="统计维度">
          <a-select
            v-decorator="['dimension', { initialValue: 'course' }]"
          >
            <a-select-option value="course">按课程</a-select-option>
            <a-select-option value="class">按班级</a-select-option>
            <a-select-option value="major">按专业</a-select-option>
            <a-select-option value="grade">按年级</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="时间范围">
          <a-range-picker v-decorator="['dateRange']" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit">查询</a-button>
          <a-button style="margin-left: 10px" @click="handleExport">导出</a-button>
        </a-form-item>
      </a-form>

      <a-divider />

      <div style="margin-bottom: 16px">
        <a-radio-group v-model="chartType" buttonStyle="solid">
          <a-radio-button value="bar">柱状图</a-radio-button>
          <a-radio-button value="pie">饼图</a-radio-button>
          <a-radio-button value="table">表格</a-radio-button>
        </a-radio-group>
      </div>

      <div v-if="chartType === 'bar'" style="height: 400px">
        <bar-chart :data="barChartData" height="400" />
      </div>

      <div v-if="chartType === 'pie'" style="height: 400px">
        <pie-chart :data="pieChartData" height="400" />
      </div>

      <a-table
        v-if="chartType === 'table'"
        :columns="columns"
        :dataSource="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <span slot="rate" slot-scope="text">
          {{ text }}%
        </span>
      </a-table>
    </a-card>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

// 柱状图组件
const BarChart = {
  template: `
    <div>
      <canvas ref="chart" class="chart-bar" :style="{'height': height + 'px'}"></canvas>
    </div>
  `,
  props: ['data', 'height'],
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.renderChart();
  },
  watch: {
    data: {
      deep: true,
      handler() {
        if (this.chart) {
          this.chart.destroy();
        }
        this.renderChart();
      }
    }
  },
  methods: {
    renderChart() {
      const ctx = this.$refs.chart.getContext("2d");
      this.chart = new Chart(ctx, {
        type: "bar",
        data: this.data,
        options: {
          indexAxis: 'x',
          layout: {
            padding: {
              top: 30,
              right: 15,
              left: 10,
              bottom: 5,
            },
          },
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: true,
              position: 'top',
            },
            tooltip: {
              enabled: true,
              mode: "index",
              intersect: false,
            },
          },
          scales: {
            y: {
              beginAtZero: true,
              grid: {
                display: true,
                color: "rgba(0, 0, 0, 0.1)",
              },
              ticks: {
                color: "#666",
                font: {
                  size: 12,
                  family: "Arial",
                },
              },
              title: {
                display: true,
                text: '人数',
                color: "#666",
              }
            },
            x: {
              grid: {
                display: false,
              },
              ticks: {
                color: "#666",
                font: {
                  size: 12,
                  family: "Arial",
                },
              },
            },
          },
        }
      });
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.destroy();
    }
  }
}

// 饼图组件
const PieChart = {
  template: `
    <div>
      <canvas ref="chart" class="chart-pie" :style="{'height': height + 'px'}"></canvas>
    </div>
  `,
  props: ['data', 'height'],
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.renderChart();
  },
  watch: {
    data: {
      deep: true,
      handler() {
        if (this.chart) {
          this.chart.destroy();
        }
        this.renderChart();
      }
    }
  },
  methods: {
    renderChart() {
      const ctx = this.$refs.chart.getContext("2d");
      this.chart = new Chart(ctx, {
        type: "pie",
        data: this.data,
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'right',
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const label = context.label || '';
                  const value = context.raw || 0;
                  const total = context.dataset.data.reduce((a, b) => a + b, 0);
                  const percentage = Math.round((value / total) * 100);
                  return `${label}: ${value} (${percentage}%)`;
                }
              }
            }
          }
        }
      });
    }
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.destroy();
    }
  }
}

const columns = [
  {
    title: '课程名称',
    dataIndex: 'courseName',
    key: 'courseName'
  },
  {
    title: '课程代码',
    dataIndex: 'courseCode',
    key: 'courseCode'
  },
  {
    title: '申请人数',
    dataIndex: 'applyCount',
    key: 'applyCount'
  },
  {
    title: '通过人数',
    dataIndex: 'approveCount',
    key: 'approveCount'
  },
  {
    title: '通过率',
    dataIndex: 'approveRate',
    key: 'approveRate',
    scopedSlots: { customRender: 'rate' }
  }
]

const tableData = [
  {
    key: '1',
    courseName: '高等数学（上）	',
    courseCode: 'MATH101',
    applyCount: 15,
    approveCount: 10,
    approveRate: 66.67
  },
  {
    key: '2',
    courseName: 'PLC与工业控制技术',
    courseCode: 'ENG101',
    applyCount: 28,
    approveCount: 22,
    approveRate: 78.57
  },
  {
    key: '3',
    courseName: '计算机基础',
    courseCode: 'CS101',
    applyCount: 8,
    approveCount: 5,
    approveRate: 62.50
  }
]

export default {
  components: {
    BarChart,
    PieChart
  },
  beforeCreate() {
    this.form = this.$form.createForm(this)
  },
  data() {
    return {
      chartType: 'bar',
      barChartData: {
        labels: ['高等数学（上）	', 'PLC与工业控制技术', '计算机基础'],
        datasets: [
          {
            label: '申请人数',
            data: [15, 28, 8],
            backgroundColor: '#1890ff',
            borderColor: '#1890ff',
            borderWidth: 1
          },
          {
            label: '通过人数',
            data: [10, 22, 5],
            backgroundColor: '#52c41a',
            borderColor: '#52c41a',
            borderWidth: 1
          }
        ]
      },
      pieChartData: {
        labels: ['高等数学（上）	', 'PLC与工业控制技术', '计算机基础'],
        datasets: [{
          data: [10, 22, 5],
          backgroundColor: [
            '#1890ff',
            '#52c41a',
            '#faad14'
          ],
          borderWidth: 1
        }]
      },
      columns,
      tableData,
      loading: false,
      pagination: {
        pageSize: 10
      }
    }
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('查询条件:', values)
          this.loading = true
          // 模拟异步查询
          setTimeout(() => {
            this.loading = false
            this.$message.success('查询成功')
            
            // 模拟更新图表数据
            this.barChartData = {
              labels: ['高等数学（上）	', 'PLC与工业控制技术', '计算机基础', '线性代数'],
              datasets: [
                {
                  label: '申请人数',
                  data: [15, 28, 8, 12],
                  backgroundColor: '#1890ff',
                  borderColor: '#1890ff',
                  borderWidth: 1
                },
                {
                  label: '通过人数',
                  data: [10, 22, 5, 9],
                  backgroundColor: '#52c41a',
                  borderColor: '#52c41a',
                  borderWidth: 1
                }
              ]
            }
            
            this.pieChartData = {
              labels: ['高等数学（上）	', 'PLC与工业控制技术', '计算机基础', '线性代数'],
              datasets: [{
                data: [10, 22, 5, 9],
                backgroundColor: [
                  '#1890ff',
                  '#52c41a',
                  '#faad14',
                  '#f5222d'
                ],
                borderWidth: 1
              }]
            }
            
            this.tableData = [
              {
                key: '1',
                courseName: '高等数学（上）	',
                courseCode: 'MATH101',
                applyCount: 15,
                approveCount: 10,
                approveRate: 66.67
              },
              {
                key: '2',
                courseName: 'PLC与工业控制技术',
                courseCode: 'ENG101',
                applyCount: 28,
                approveCount: 22,
                approveRate: 78.57
              },
              {
                key: '3',
                courseName: '计算机基础',
                courseCode: 'CS101',
                applyCount: 8,
                approveCount: 5,
                approveRate: 62.50
              },
              {
                key: '4',
                courseName: '线性代数',
                courseCode: 'MATH102',
                applyCount: 12,
                approveCount: 9,
                approveRate: 75.00
              }
            ]
          }, 800)
        }
      })
    },
    handleExport() {
      this.$message.info('导出免修统计报表')
    }
  }
}
</script>

<style scoped>
.chart-bar {
  width: 100%;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-pie {
  width: 100%;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>